//
//  RHAddPlant2Cell.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/2.
//

#import "RHAddMePlantCell.h"
#import "RHAddCommonModel.h"
#import "RHMeSystemModel.h"
NSString *const AddPlantCell_Normal   = @"AddPlantCell_Normal";
NSString *const AddPlantCell_Select   = @"AddPlantCell_Select";
NSString *const AddPlantCell_Location = @"AddPlantCell_Location";




@interface RHAddPlantSystemItemCell()

@property (nonatomic ,strong) QMUILabel *systemNameLab;

@end
@implementation RHAddPlantSystemItemCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]){
        [self setupUI];
    }
    return self;
}

-(void)setSystemName:(NSString *)systemName
{
    self.systemNameLab.text = systemName;
   
}

- (void)setupUI{
    kWeakSelf;
    self.contentView.backgroundColor = UIColor.whiteColor;
    UIView *bgView = [[UIView alloc] init];
    [bgView setBackgroundColor:CFTabViewBgColor];
    [self.contentView addSubview:bgView];
    [bgView rounded:8];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(3,15, 3, 15));
        make.height.mas_equalTo(38);
    }];
    
    _systemNameLab = [QMUILabel labelWithFont:kSYSTEMFONT(14) textColor:kCOLOR_HEX(@"3F4443") textAligment:NSTextAlignmentLeft];
    _systemNameLab.numberOfLines = 0;
    [bgView addSubview:_systemNameLab];
  
    [_systemNameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
        make.right.mas_offset(-15);
    }];
}

@end




//===================================================================================




@interface RHAddMePlantCell()<QMUITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic, strong) UIView *bgView;

@property (nonatomic ,strong) QMUILabel *titleLab;

@property (nonatomic ,strong) QMUITextField *textField;

@property (nonatomic ,strong) UIImageView *arrowImg;

@property (nonatomic ,strong) QMUIButton *locationBtn;
@end
@implementation RHAddMePlantCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]){
        [self setupUI];
    }
    return self;
}

-(void)setModel:(RHAddCommonModel *)model
{
    _model = model;
    NSString *title;
    if (model.isRequired) {
        title = [NSString stringWithFormat:@"*%@",model.title];
        self.titleLab.attributedText = [NSString attributeStringWithContent:title attriFont:kSYSTEMFONT(14) attriColor:kCOLOR_HEX(@"#F95454") attriKey:@"*"];
    }else{
        self.titleLab.text = model.title;
    }
    
    self.textField.placeholder = model.placeHolder;
    self.textField.text = model.content;
    if ([model.tag isEqualToString:@"plant_date"]) {
        if ([model.content integerValue]>0) {
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:[model.content integerValue]/1000.0];
            self.textField.text = [date stringWithFormat:@"yyyy-MM-dd"];
        }else{
            self.textField.text = nil;
        }
        
    }
    if (self.model.systemList.count>0) {
        self.textField.text = [NSString stringWithFormat:@"%ld%@",self.model.systemList.count,@"个".rh_localized];
    }else if(self.model.deviceList.count>0){
        self.textField.text = [NSString stringWithFormat:@"%ld%@",self.model.deviceList.count,@"个".rh_localized];
    }
    
    if (model.isSelection) {
        [model.optionList enumerateObjectsUsingBlock:^(RHMeOptionTypeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([model.content integerValue] == obj.typeId) {
                if (model.content.length>0) {
                    self.textField.text = obj.typeName.rh_localized;
                }else{
                    self.textField.text = nil;//显示placeHolder
                }
                
            }
        }];
    }
    
    
    if (model.isFirst) {
        self.bgView.layer.cornerRadius = 8;
        self.bgView.qmui_borderColor = kBorderColor;
        self.bgView.qmui_borderWidth = 1;
        self.bgView.qmui_borderPosition = QMUIViewBorderPositionLeft|QMUIViewBorderPositionRight|QMUIViewBorderPositionTop;
        self.bgView.layer.qmui_maskedCorners = QMUILayerMinXMinYCorner|QMUILayerMaxXMinYCorner;
    }else if (model.isLast){
        self.bgView.layer.cornerRadius = 8;
        self.bgView.qmui_borderColor = kBorderColor;
        self.bgView.qmui_borderWidth = 1;
        self.bgView.qmui_borderPosition = QMUIViewBorderPositionLeft|QMUIViewBorderPositionRight|QMUIViewBorderPositionBottom;
        self.bgView.layer.qmui_maskedCorners = QMUILayerMinXMaxYCorner|QMUILayerMaxXMaxYCorner;
    }else{
        self.bgView.layer.cornerRadius = 0;
        self.bgView.qmui_borderPosition = QMUIViewBorderPositionLeft|QMUIViewBorderPositionRight;
        self.bgView.qmui_borderColor = kBorderColor;
        self.bgView.qmui_borderWidth = 1;
    }
    kWeakSelf;
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.offset(weakSelf.model.systemList.count*44);
        make.bottom.mas_offset(weakSelf.model.systemList.count>0?-15:0);
    }];
    [self.tableView reloadData];
}


- (void)setupUI{
    kWeakSelf;
    self.contentView.backgroundColor = CFTabViewBgColor;
    UIView *bgView = [[UIView alloc] init];
    [bgView setBackgroundColor:UIColor.whiteColor];
    [self.contentView addSubview:bgView];
    self.bgView = bgView;
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(0);
        make.bottom.mas_offset(0);
    }];
    
    UIView *topContentView = kView;
    [bgView addSubview:topContentView];
    [topContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_offset(0);
        make.height.offset(50);
    }];
    
    _titleLab = [[QMUILabel alloc] init];
    [_titleLab setTextAlignment:NSTextAlignmentLeft];
    _titleLab.numberOfLines = 0;
    [_titleLab setFont:[UIFont systemFontOfSize:14]];
    [_titleLab setTextColor:kCOLOR_HEX(@"3F4443")];
    [topContentView addSubview:_titleLab];
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
        make.width.mas_equalTo(kScaleW(100));
    }];
    
     _arrowImg= [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow"]];
    [topContentView addSubview:_arrowImg];
    [_arrowImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(15);
        make.centerY.mas_offset(0);
        make.right.mas_offset(-15);
    }];
 
    _textField = [[QMUITextField alloc] init];
    [_textField setTextAlignment:NSTextAlignmentRight];
    [_textField setTextColor:[kCOLOR_HEX(@"3F4443") colorWithAlphaComponent:0.8]];
    [_textField setFont:[UIFont systemFontOfSize:14]];
    _textField.delegate = self;
    [topContentView addSubview:_textField];
    [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.titleLab.mas_right).offset(5);
        make.right.equalTo(weakSelf.arrowImg.mas_left).offset(-5);
        make.height.mas_equalTo(30);
        make.centerY.mas_offset(0);
    }];
    
    
    UIView *lineV = [[UIView alloc] init];
    [lineV setBackgroundColor:CFCellLineColor];
    [bgView addSubview:lineV];
    [lineV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.bottom.mas_offset(0);
        make.height.mas_equalTo(1);
    }];
    
    _arrowImg.hidden = YES;
    if ([self.reuseIdentifier isEqualToString:AddPlantCell_Select]) {//选择项
        _arrowImg.hidden = NO;
        
        QMUIButton *clickBtn = [[QMUIButton alloc]init];
        [topContentView addSubview:clickBtn];
        [clickBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(10, 15, 10, 15));
        }];
        
        [[clickBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            if(weakSelf.clickBlock){
                weakSelf.clickBlock();
            }
        }];
    }
    if ([self.reuseIdentifier isEqualToString:AddPlantCell_Location]) {
        _arrowImg.hidden = NO;
//        _locationBtn = [QMUIButton buttonWithImage:@"location_icon"];
//        [topContentView addSubview:_locationBtn];
//        [_locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.width.height.offset(35);
//            make.right.mas_offset(-15);
//            make.centerY.mas_offset(0);
//        }];
//        
        QMUIButton *clickBtn = [[QMUIButton alloc]init];
        [topContentView addSubview:clickBtn];
        [clickBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(10, 15, 10, 15));
        }];
        
        [[clickBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            if(weakSelf.clickBlock){
                weakSelf.clickBlock();
            }
        }];
//        
//        [_arrowImg mas_remakeConstraints:^(MASConstraintMaker *make) {
//            make.width.height.offset(15);
//            make.centerY.mas_offset(0);
//            make.right.equalTo(weakSelf.locationBtn.mas_left).offset(0 );
//        }];
//        [[_locationBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
//            if (weakSelf.locationBlock) {
//                weakSelf.locationBlock();
//            }
//        }];
    }
    
   
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHAddPlantSystemItemCell class] forCellReuseIdentifier:@"RHAddPlantSystemItemCell"];
    _tableView.scrollEnabled = NO;
    [bgView addSubview:_tableView];
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    } else {
        // Fallback on earlier versions
    }
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(0);
        make.right.mas_offset(-0);
        make.top.equalTo(topContentView.mas_bottom).offset(0);
        make.bottom.mas_offset(-0);
        make.height.offset(0);
    }];

}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.model.systemList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHAddPlantSystemItemCell *itemCell = [tableView dequeueReusableCellWithIdentifier:@"RHAddPlantSystemItemCell"];
    RHMeSystemModel *systemModel = self.model.systemList[indexPath.row];
    [itemCell setSystemName:systemModel.systemName];
    return itemCell;
}



-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.model.content = textField.text;
    //电站经纬度判断 经度-180 到180  纬度-90 到 90
    if ([self.model.tag isEqualToString:@"plant_longitude"]) {
        if ([textField.text doubleValue]<-180) {
            textField.text = @"-180";
            self.model.content = textField.text;
        }
        if ([textField.text doubleValue]>180) {
            textField.text = @"180";
            self.model.content = textField.text;
        }
    }
    if ([self.model.tag isEqualToString:@"plant_latitude"]) {
        if ([textField.text doubleValue]<-90) {
            textField.text = @"-90";
            self.model.content = textField.text;
        }
        if ([textField.text doubleValue]>90) {
            textField.text = @"90";
            self.model.content = textField.text;
        }
    }
}


-(BOOL)textField:(QMUITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //删除
    if ([string isEqualToString:@""]) {
        return YES;
    }
    if ([self.titleLab.text isEqualToString:@"电价配置".rh_localized]) {
        if ([textField.text containsString:@"."]) {
            //有小数点就不让再次输入小数点
            if ([string containsString:@"."]||textField.text.length == textField.maximumTextLength) {
                return NO;
            }
            //只能输入两位小数
            //小数点的位置
            NSRange point_range = [textField.text rangeOfString:@"."];
            //在小数点前面可以输入
            if (range.location <= point_range.location) {
                return YES;
            }
            NSString *pointValue = [textField.text substringFromIndex:point_range.location+1];
            NSLog(@"------>%@",pointValue);
            if (pointValue.length>=2) {
                return NO;
            }
            return YES;
        }else{
            //没有小数点存在,如果第一个输入的是小数点,自动补0
            if ([string isEqualToString:@"."]&&textField.text.length == 0) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    textField.text = [NSString stringWithFormat:@"0%@",string];
                });
                return YES;
            }
        }
    }else{
        //其他的按照最大长度限制
        if (textField.text.length>textField.maximumTextLength) {
            return NO;
        }
    }
    return YES;
}

@end
